package cn.javaweb.group0.model;

import cn.javaweb.entity.User;
import cn.javaweb.group0.entity.Role;
import cn.javaweb.model.BaseModel;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class RoleModel extends BaseModel {

    public Object parseObject(ResultSet rs){
        Role role = new Role();
        try{
            role.setId(rs.getInt("id"));
            role.setName(rs.getString("name"));
            role.setRemark(rs.getString("remark"));
            return role;
        }catch (Exception e){

        }
        return null;

    }

    public List<String> getRoles(User user){
        String sql = "SELECT role.* FROM `role`,`user_role` where role.id = user_role.user_id and user_role.user_id=?";

        Object [] params = {user.getId()};
        List<Object> list = this.selectAll(sql, params);
        List<String> result = new ArrayList<String>();
        for(Object item:list){
            result.add(((Role)item).getName());
        }
        return result;
    }

    public List<String> getRolesByUser(User user){
        List<String> result = new ArrayList<String>();
        String sql = "select * from user u, role r, user_role ur "+
                     " where u.id=ur.user_id and r.id=ur.role_id "+
                     " and u.id=?";
        Object [] params = {user.getId()};

        List<Object> list = this.selectAll(sql, params);

        for(Object o:list){
            Role r = (Role)o;
            result.add(r.getName());
        }

        return result;
    }
}
